from flask import Blueprint, request, jsonify
from app import db
from models.user import User
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint('auth', __name__, url_prefix='/api/auth')

@bp.route('/register', methods=['POST'])
def register():
    """
    用户注册接口
    """
    try:
        data = request.get_json()
        
        # 检查必需字段
        required_fields = ['username', 'email', 'password']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必需字段: {field}',
                    'data': None
                }), 400
        
        # 检查用户是否已存在
        if User.query.filter_by(username=data['username']).first():
            return jsonify({
                'code': 400,
                'message': '用户名已存在',
                'data': None
            }), 400
            
        if User.query.filter_by(email=data['email']).first():
            return jsonify({
                'code': 400,
                'message': '邮箱已被注册',
                'data': None
            }), 400
        
        # 创建新用户
        user = User(
            username=data['username'],
            email=data['email'],
            password_hash=generate_password_hash(data['password'])
        )
        
        db.session.add(user)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '用户注册成功',
            'data': user.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'注册失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/login', methods=['POST'])
def login():
    """
    用户登录接口
    """
    try:
        data = request.get_json()
        
        # 检查必需字段
        if 'username' not in data or 'password' not in data:
            return jsonify({
                'code': 400,
                'message': '缺少用户名或密码',
                'data': None
            }), 400
        
        # 查找用户
        user = User.query.filter_by(username=data['username']).first()
        
        # 验证用户
        if not user or not check_password_hash(user.password_hash, data['password']):
            return jsonify({
                'code': 401,
                'message': '用户名或密码错误',
                'data': None
            }), 401
        
        # 生成访问令牌，将用户ID转换为字符串
        access_token = create_access_token(identity=str(user.id))
        
        return jsonify({
            'code': 200,
            'message': '登录成功',
            'data': {
                'access_token': access_token,
                'user': user.to_dict()
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'登录失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/profile', methods=['GET'])
@jwt_required()
def profile():
    """
    获取用户信息接口
    """
    try:
        current_user_id = get_jwt_identity()
        # 将字符串ID转换为整数进行查询
        user = User.query.get(int(current_user_id))
        
        if not user:
            return jsonify({
                'code': 404,
                'message': '用户不存在',
                'data': None
            }), 404
            
        return jsonify({
            'code': 200,
            'message': '获取用户信息成功',
            'data': user.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取用户信息失败: {str(e)}',
            'data': None
        }), 500